package cc.vv.lkrouter.router;

import android.support.v4.app.Fragment;

import java.util.concurrent.ConcurrentHashMap;

import cc.vv.lkrouter.inter.RouterInter;

/**
 * android.support.v4.app.Fragment路由配置
 *
 * @author: NPF
 * @date: 2018/3/12.
 */
public class RouterV4Fragment implements RouterInter<Fragment, Class<? extends Fragment>> {

    /**
     * 路由缓存
     */
    private ConcurrentHashMap<String, Class<? extends Fragment>> mClassZ = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, Fragment> mClassF = new ConcurrentHashMap<>();

    private static RouterV4Fragment mInstance;

    private RouterV4Fragment() {
    }

    public static RouterV4Fragment getInstance() {
        if (null == mInstance) {
            synchronized (RouterV4Fragment.class) {
                if (null == mInstance) {
                    mInstance = new RouterV4Fragment();
                }
            }
        }
        return mInstance;
    }

    /**
     * Fragment实例配置
     *
     * @param key      唯一键
     * @param fragment fragment
     */
    @Override
    public void routerT(String key, Fragment fragment) {
        Fragment cacheFragment = mClassF.get(key);
        if (null == cacheFragment || fragment != cacheFragment) {
            mClassF.put(key, fragment);
        }
    }

    /**
     * Fragment实例获取
     *
     * @param key 唯一键
     * @return Fragment实例获取
     */
    @Override
    public Fragment invokT(String key) {
        return mClassF.get(key);
    }

    /**
     * Fragment字节码配置
     *
     * @param key    唯一键
     * @param classz Fragment字节码
     */
    @Override
    public void routerV(String key, Class<? extends Fragment> classz) {
        Class<? extends Fragment> cacheClass = mClassZ.get(key);
        if (null == cacheClass || classz != cacheClass) {
            mClassZ.put(key, classz);
        }
    }

    /**
     * Fragment字节码获取
     *
     * @param key 唯一键
     * @return Fragment字节码
     */
    @Override
    public Class<? extends Fragment> invokV(String key) {
        return mClassZ.get(key);
    }
}
